package com.qianchang.microfinance.view.mine;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.widget.Button;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.MD5Util;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.utils.ViewUtils;
import com.dm.library.widgets.OneLineEditLinearLayout;
import com.dm.library.widgets.OneLineLinearLayout;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.api.InputTradPwdApi;
import com.qianchang.microfinance.bean.BankCardBean;
import com.qianchang.microfinance.bean.FeeBean;
import com.qianchang.microfinance.bean.MineUserInfo;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.mine.loan.LoanProgressActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qianchang.microfinance.view.mine.RechargeActivity.RequestCode;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: 提现
 * 修 改 人: zhoulai
 * 修改时间: 2017/8/14 17:27
 */


public class WithDrawActivity extends BaseActivity {

    @BindView(R.id.oll_bank_card)
    OneLineLinearLayout ollBankCard;
    @BindView(R.id.oll_can_withdraw_amount)
    OneLineLinearLayout ollCanWithdrawAmount;
    @BindView(R.id.ole_input_withdraw_amount)
    OneLineEditLinearLayout oleInputWithdrawAmount;
    @BindView(R.id.oll_fee)
    OneLineLinearLayout ollFee;
    @BindView(R.id.oll_receipt_amount)
    OneLineLinearLayout ollReceiptAmount;
    @BindView(R.id.btn_withdraw)
    Button btnWithdraw;
    private FeeBean feeBean;
    private double withdrawAmount;//输入的提取金额
    private double arrivalAmount;//到账金额
    private BankCardBean bankCardBean;
    private MineUserInfo mineUserInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdraw);
        ButterKnife.bind(this);
        setTitleName(getString(R.string.withdraw));
        initView();
        initData();
    }

    @Override
    protected void initView() {
        super.initView();
        oleInputWithdrawAmount.setInputType(InputType.TYPE_CLASS_NUMBER);
        oleInputWithdrawAmount.setTextWatcher(new OneLineEditLinearLayout.TextWatcher() {
            @Override
            public void afterTextChanged(Editable s, int flag) {
                if (s.toString().length() > 8) {//限制八个字符
                    withdrawAmount = StringUtils.toDouble(s.toString().trim().substring(0, 8));
                    oleInputWithdrawAmount.setRightContent(withdrawAmount + "");
                } else {
                    withdrawAmount = StringUtils.toDouble(s.toString().trim());
                }

                if (feeBean == null) return;
                //显示手续费
                if (feeBean != null) {
                    if (feeBean.getFeePay() == 0) {//充值手续费支付：0个人 1.平台;是平台支付不需要显示手续费
                        ollFee.setRightContent(FormatUtil.numKbPointFormat(feeBean.getFee()));
                        //手续费支付方式：0:内扣，从提现金额里面扣，1：外扣，提现金额+提现手续费)
                        switch (feeBean.getFeeType()) {
                            case "0":
                                ollReceiptAmount.setRightContent(FormatUtil.numKbPointFormat(withdrawAmount - feeBean.getFee()));
                                break;
                            case "1":
                                ollReceiptAmount.setRightContent(FormatUtil.numKbPointFormat(withdrawAmount));
                                break;
                        }
                    } else {//平台带扣，不需要支付手续费
                        ollFee.setRightContent(FormatUtil.numKbPointFormat(0));
                        ollReceiptAmount.setRightContent(FormatUtil.numKbPointFormat(withdrawAmount));
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (bundle != null) {
            mineUserInfo = (MineUserInfo) bundle.getSerializable(MineUserInfo.class.getName());
            bankCardBean = (BankCardBean) bundle.getSerializable(BankCardBean.class.getName());
            refresh(bankCardBean);
            if (mineUserInfo != null) {
                ollCanWithdrawAmount.setRightContent(FormatUtil.numKbPointFormat(mineUserInfo.getAvailable()));
            } else {
                mineUserInfo = new MineUserInfo();
            }
        }
        findWithdrawFee();
    }

    private void findWithdrawFee() {
        show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_WITH_DRAW_FEE, params, new RequestCallBack<FeeBean>() {
            @Override
            public void onSuccess(JsonResult<FeeBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    feeBean = response.getObject();
                    //需求：在用户输入金额的时候再显示手续费
                } else {
                    ToastUtil.getInstant().show(WithDrawActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(WithDrawActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void refresh(BankCardBean bankCardBean) {
        if (bankCardBean == null) {
            showDataError();
            return;
        }
        ollBankCard.setRightContent(ViewUtils.formatBankCard(bankCardBean.getBankCardNumber()));
        ollBankCard.setLeftContent(bankCardBean.getBankName());
    }


    @OnClick(R.id.btn_withdraw)
    public void onViewClicked() {
        if (withdrawAmount == 0) {
            ToastUtil.getInstant().show(WithDrawActivity.this, getString(R.string.msg_input_withDraw));
            return;
        }
        if (feeBean != null) {
            if (withdrawAmount > feeBean.getMaxAmount() || withdrawAmount < feeBean.getMinAmount()) {
                String msg = getString(R.string.msg_withDraw_max_min)
                        + FormatUtil.numKbPointFormat(feeBean.getMinAmount())
                        + "-"
                        + FormatUtil.numKbPointFormat(feeBean.getMaxAmount())
                        + "元";
                ToastUtil.getInstant().show(WithDrawActivity.this, msg);
                return;
            }
        }
        if (withdrawAmount > mineUserInfo.getAvailable()) {
            ToastUtil.getInstant().show(WithDrawActivity.this, getString(R.string.msg_withDraw_too_big));
            return;
        }
        //判断有无交易密码
        InputTradPwdApi.checkHasTradPwd(WithDrawActivity.this, new InputTradPwdApi.PwdCallBack() {
            @Override
            public void commit(String password) {
                submit(password);
            }
        });

/*
        InputPwdDialog inputDialog = new InputPwdDialog(this);
        inputDialog.setForgetPwdListener(new InputPwdDialog.ForgetPwdListener() {
            @Override
            public void forgetPwd() {
                Intent intent = new Intent(WithDrawActivity.this, ForgetActivityOne.class);
                intent.putExtra(SettingTradPasswordActivity.IS_TRAD_PWD, true);
                startActivity(intent);
            }
        });
        inputDialog.setOnInputFinishListener(new InputPwdDialog.OnInputFinishListener() {
            @Override
            public void finish(String password) {
                submit(password);
            }
        });
        inputDialog.show();
*/
    }

    //提现
    private void submit(String password) {
        if (withdrawAmount == 0) {
            ToastUtil.getInstant().show(this, getString(R.string.please_input_withdraw_amount));
            return;
        }
        HttpParams params = new HttpParams();
        params.put("tradePwd", MD5Util.string2MD5(password + ConstantAppInfo.Password.PASSWORD_SUFFIX));
        params.put("amount", withdrawAmount);//String	11	Y	充值金额
        params.put("paidType", "3");//	50	Y	支付方式: 01.微信 02.支付宝 03.储蓄卡充值
        if (feeBean != null) {
            params.put("fee", feeBean.getFee());
        }
//        params.put("thirdCompany", "第三方支付公司");//	String	50	N	第三方支付公司
        if (bankCardBean != null) {
            params.put("bankCardId", bankCardBean.getBankId());//    	String	50	N	银行卡id
        }
        show();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.WITH_DRAW, params, new RequestCallBack<FeeBean>() {
            @Override
            public void onSuccess(JsonResult<FeeBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    InputTradPwdApi.dismiss();
                    Bundle bundle = new Bundle();
                    bundle.putDouble(WithDrawActivity.class.getName(), withdrawAmount);
                    startActivityForResult(LoanProgressActivity.class, bundle, RequestCode);
                } else {
                    ToastUtil.getInstant().show(WithDrawActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(WithDrawActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RequestCode) {
            finish();
        }
    }

}
